# -*- coding: utf-8 -*-

from qiniu import Auth, put_file, etag, urlsafe_base64_encode, put_data,put_file
from qiniu import BucketManager
from app.setting import API_SET
import random
import time
import requests
from urllib import parse
import base64



# 需要填写你的 Access Key 和 Secret Key
access_key = API_SET["QINIU"]["access_key"]
secret_key = API_SET["QINIU"]["secret_key"]
bucket_name = API_SET["QINIU"]["bucket_name"]
notifyURL = API_SET["QINIU"]["callback"]
bucket_url = API_SET["QINIU"]["qiniu_url"]
def img_name():
    seed = "1234567890abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ_-"
    sa = []
    for i in range(9):
        sa.append(random.choice(seed))
    salt = ''.join(sa)
    return str(int(time.time()))+ salt

#上传文件
def storage(file_data):
    """
    上传图片到七牛
    file_data是文件的二进制数据
    key 是名字
    """
    # 构建鉴权对象
    q = Auth(access_key, secret_key)

    # 要上传的空间
    # 我们不需要这个Key. 七牛会自动生成
    # 上传到七牛后保存的文件名


    # 生成上传 Token，可以指定过期时间等
    key = img_name()


    token = q.upload_token(bucket_name, key, 3600)

    # 我们这个是通过form表单提交的, 不需要用到put_file方法
    # 要上传文件的本地路径
    # localfile = './sync/bbb.jpg'
    # ret, info = put_file(token, None, file_data)

    ret, info = put_data(token, key, file_data)

    print('info: %s' % info)

    print('ret: %s' % ret)


    if info.status_code == 200:
        # 表示上传成功， 返回文件名
        # 我们上传成功之后, 需要在别的页面显示图像, 因此需要返回图像名
        return ret.get("key")
    else:
        # 表示上传失败
        raise Exception("上传失败")
        # http://ozcxm6oo6.bkt.clouddn.com/FnTUusE1lgSJoCccE2PtYIt0f7i3
#删除文件
def delect(key):
    q = Auth(access_key, secret_key)
    # 初始化BucketManager
    bucket = BucketManager(q)
    # 你要测试的空间， 并且这个key在你空间中存在
    # 删除bucket_name 中的文件 key
    ret, info = bucket.delete(bucket_name, key)
    print(info)
    if info.status_code == 200:
        return True
    else:
        return False
#获取token
def utoken(key):
    q = Auth(access_key, secret_key)

    # 我们不需要这个Key. 七牛会自动生成
    # 上传到七牛后保存的文件名

    # 生成上传 Token，可以指定过期时间等
    token = q.upload_token(bucket_name, key, 3600*6)

    return {"utoken":token,"key":key}

#获取token
def utoken_policy(key,policy):
    '''

    :param key: 文件名
    :param policy: 配置项
    :return:
    '''
    q = Auth(access_key, secret_key)


    # 生成上传 Token，可以指定过期时间等
    token = q.upload_token(bucket_name, key, 3600*6,policy)

    return {"utoken":token,"key":key}

#触发m3u8转码
def pfop_m3u8(key,wmText):
    q = Auth(access_key, secret_key)
    pattern = key + "$(count)"
    pattern = str(base64.b64encode(pattern.encode("utf-8")),"utf-8")
    wmText = "@"+wmText
    fops = f'avthumb/m3u8/noDomain/0/domain/{str(base64.b64encode(parse.urlparse(bucket_url).netloc.encode("utf-8")), "utf8")}/segtime/15/vb/256k/pattern/{pattern}'
    fops +=f'/wmText/{str(base64.urlsafe_b64encode(wmText.encode("utf8")),"utf8")}/wmFont/6buR5L2T/wmFontColor/I2JmYmZiZg0K/wmFontSize/48/wmOffsetX/-20/wmOffsetY/20/wmGravityText/NorthEast'
    api_url = f'http://api.qiniu.com/pfop/?'
    api_url += f'bucket={parse.quote(bucket_name)}&key={parse.quote(key)}&fops={parse.quote(fops)}'
    api_url += f'&force=1&notifyURL={parse.quote(notifyURL+"pdd/qiniu/callback/m3u8")}'
    content_type = 'application/x-www-form-urlencoded'
    authorization = q.token_of_request(url=api_url,content_type=content_type)
    headers = {
        'Authorization': 'QBox ' + authorization,
        'Host': 'api.qiniu.com',
        'Content-Type': content_type,
    }

    res = requests.post(api_url, headers=headers, timeout=30)
    return res.json()

#视频截图
def vframe(key):
    q = Auth(access_key, secret_key)
    api_url = f'http://api.qiniu.com/pfop/?bucket={bucket_name}&key={key}&fops=vframe/png/offset/2/w/480/h/360&notifyURL={notifyURL}zgc/qiniu/callback&force=1&pipeline=vframe'
    content_type = 'application/x-www-form-urlencoded'
    authorization = q.token_of_request(url=api_url, content_type=content_type)
    headers = {
        'Authorization': 'QBox ' + authorization,
        'Host': 'api.qiniu.com',
        'Content-Type': content_type,
    }
    res = requests.post(api_url, headers=headers, timeout=30)
    print(res.content)
    print(res.status_code)
    print(res.headers)
    return res

#视频时长间隔截图
def vsample(key):
    q = Auth(access_key, secret_key)
    avinfo = requests.post(url=f"http://qdt950tnf.bkt.clouddn.com/{key}?avinfo")
    duration = int(float(avinfo.json().get("streams")[0].get("duration")))
    interval = int(duration/4)
    api_url = f'http://api.qiniu.com/pfop/?bucket={bucket_name}&key={key}&fops=vsample/jpg/ss/0/t/{duration}/interval/{interval}/pattern/dmZyYW1lLSQoY291bnQp&notifyURL={notifyURL}zgc/qiniu/callback&force=1&pipeline=vsample'
    content_type = 'application/x-www-form-urlencoded'
    authorization = q.token_of_request(url=api_url, content_type=content_type)
    headers = {
        'Authorization': 'QBox ' + authorization,
        'Host': 'api.qiniu.com',
        'Content-Type': content_type,
    }
    res = requests.post(api_url, headers=headers, timeout=30)
    print(res.content)
    print(res.status_code)
    print(res.headers)
    return res
